<template>
  <div>
    <Button type="primary" class="back-button" @click="$router.push({path:'/integral-calculation-management/calculation/add-start'})" icon="md-arrow-back">返回上一级</Button>
    <Card>
      <Row>
        <Table stripe border :columns="tableColumnsShow" :data="tableData"></Table>
      </Row>
    </Card>
    <Card class="m-t-sm center" v-if="!isQuery">
      <Row class="m-t-lg m-b-lg">
        <Icon type="md-calculator" style="font-size:80pt;" />
        <br>
        <Button class="m-r-sm" type="primary" size="large" :disabled='!model.athleteNum' @click="reckon2" shape="circle">19年年度排名</Button>
        <Button class="m-r-sm" type="primary" size="large" :disabled='!model.athleteNum' @click="reckon" shape="circle">开始计算</Button>
        <Button class="" type="primary" size="large" :disabled='!model.athleteNum' @click="scheduledTask" shape="circle">定时计算</Button>
        <task-model :visible.sync="visible" :model-temp="scheduledModel"></task-model>
      </Row>
    </Card>
    <Row class="m-t-lg" v-if="isQuery">
      <Button class="m-r-sm" @click="cancel">放弃计算</Button>
      <Button type="primary" @click="save">保存</Button>
    </Row>
    <Card class="m-t-sm" v-if="isQuery">
      <Table stripe border :columns="rankColumns" :data="rankData"></Table>
      <page-temp :total="total" :current="page.pageNo" :size="page.pageSize" @changePage='changePage'></page-temp>
    </Card>
    <spin-temp v-if="loading"></spin-temp>
  </div>
</template>

<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import taskModel from "_c/calculation/task-modal.vue";
import { getDict } from "@/api/configure";
import Api from "@/api/calculation";
import _ from "lodash";
const api = new Api();
// 赛事管理
export default {
  components: {
    dict,
    dictSpan,
    taskModel
  },
  data() {
    return {
      loading: true,
      visible: false,
      isQuery: false,
      rankId: null,
      model: {
        ruleId: this.$route.params.ruleId,
        ranktype: this.$route.params.ranktype,
        handlers: this.$store.state.user.userName,
        countTime: new Date().getTime()
      },
      //定时弹框对象
      scheduledModel: {},
      page: {
        pageSize: this.$config.PAGE_SIZE,
        pageNo: 1
      },
      AGOUTS: [],
      rankColumns: [
        {
          title: "本周排名",
          key: "showRank",
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: this.$config.getColor(
                    params.row.showRank,
                    params.row.lastRank
                  )
                }
              },
              params.row.showRank
            );
          }
        },
        {
          title: "上周排名",
          key: "lastRank",
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              params.row.lastRank == null ? "--" : params.row.lastRank
            );
          }
        },
        {
          title: "选手名称",
          key: "userName",
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              this.$config.userName(params.row.userName, params.row.englishName)
            );
          }
        },
        {
          title: "国籍",
          key: "country",
          align: "left",
          render: (h, params) => {
            let self = this;
            let row = self.AGOUTS.find(x => x.code === params.row.country) || {
              name: params.row.country
            };
            return h("span", row.name);
          }
        },
        {
          title: "参赛场次",
          key: "sum",
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              (params.row.sum == null ? 0 : params.row.sum) + "场"
            );
          }
        },
        {
          title: "积分",
          key: "avg",
          align: "left",
          render: (h, params) => {
            return h("span", this.$config.toIntegral(params.row.avg));
          }
        }
      ],
      rankData: [],
      rankDataSource: [],
      total: 0,
      tableColumnsShow: [
        {
          title: "计算规则",
          key: "ruleId",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h(dictSpan, {
              props: {
                code: "JSGZ",
                value: self.model.ruleId
              }
            });
          }
        },
        {
          title: "选手数量",
          key: "athleteNum",
          align: "left"
        },
        {
          title: "操作者",
          key: "handlers",
          align: "left"
        },
        {
          title: "计算时间",
          key: "countTime",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h(
              "span",
              self.$moment(params.row.countTime).format("YYYY-MM-DD HH:mm:ss")
            );
          }
        }
      ],
      tableData: []
    };
  },
  mounted() {
    let self = this;
    getDict({ code: "AG_OUT" })
      .then(data => {
        self.AGOUTS = data;
        self.init();
      })
      .catch(error => {
        self.init();
      });
  },
  computed: {
    cardHeight: function() {
      return `${document.documentElement.clientHeight - 285}px`;
    }
  },
  methods: {
    // 初始化
    init() {
      let self = this;
      api
        .getPlayersNumber({
          ruleId: self.model.ruleId,
          ranktype: self.model.ranktype
        })
        .then(data => {
          self.model.kindRule = self.model.ruleId;
          self.model.athleteNum = data.count;
          self.model.startTime = data.startTime;
          self.model.endTime = data.endTime;
          self.model.rankYear = data.rankYear;
          self.model.rankWeek = data.rankWeek;
          self.model.kindCode = data.kindCode;
          self.tableData = [self.model];
          self.loading = false;
        })
        .catch(error => {
          self.tableData = [self.model];
          self.loading = false;
        });
    },
    // 计算
    reckon2() {
      let self = this;
      self.loading = true;
      let params = _.pick(self.model, [
        "athleteNum",
        "handlers",
        "kindRule",
        "countTime",
        "rankYear",
        "rankWeek",
        "kindCode"
      ]);

      let paramsReckon = _.pick(self.model, [
        "ruleId",
        "ranktype",
        "startTime",
        "endTime"
      ]);
      if (self.model.kindCode == "1") {
        params.startCountcycletime = this.$moment("2018-01-01").valueOf();
        paramsReckon.startTime = this.$moment("2018-01-01").valueOf();
      } else {
        params.startCountcycletime = this.$moment("2019-01-01").valueOf();
        paramsReckon.startTime = this.$moment("2019-01-01").valueOf();
      }
      params.endCountcycletime = this.$moment("2019-12-31 23:59:59").valueOf();
      paramsReckon.endTime = this.$moment("2019-12-31 23:59:59").valueOf();
      api
        .add([params])
        .then(data => {
          self.rankId = data;
          paramsReckon.rankId = data;
          return api.reckon(paramsReckon);
        })
        .then(data => {
          self.rankDataSource = data;
          self.changePage(1);
          self.loading = false;
          self.isQuery = true;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    // 计算
    reckon() {
      let self = this;
      self.loading = true;
      let params = _.pick(self.model, [
        "athleteNum",
        "handlers",
        "kindRule",
        "countTime",
        "rankYear",
        "rankWeek",
        "kindCode"
      ]);
      params.startCountcycletime = self.model.startTime;
      params.endCountcycletime = self.model.endTime;
      let paramsReckon = _.pick(self.model, [
        "ruleId",
        "ranktype",
        "startTime",
        "endTime"
      ]);
      api
        .add([params])
        .then(data => {
          self.rankId = data;
          paramsReckon.rankId = data;
          return api.reckon(paramsReckon);
        })
        .then(data => {
          self.rankDataSource = data;
          self.changePage(1);
          self.loading = false;
          self.isQuery = true;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    // 自动计算
    scheduledTask() {
      this.scheduledModel = _.pick(this.model, ["ruleId", "weekNum", "time"]);
      this.visible = true;
    },
    fetchList() {
      let self = this;
      self.rankData = self.rankDataSource.slice(
        (self.page.pageNo - 1) * self.page.pageSize,
        self.page.pageNo * self.page.pageSize
      );
      self.total = self.rankDataSource.length || 0;
    },
    // 分页
    changePage(pageNum) {
      this.page.pageNo = pageNum;
      this.fetchList();
    },
    // 放弃计算
    cancel() {
      let self = this;
      api.del([self.rankId]).then(flag => {
        self.$router.push({
          path: "/integral-calculation-management/calculation/add-start"
        });
      });
    },
    // 保存计算
    save() {
      let self = this;
      self.loading = true;
      self.rankDataSource.forEach(x => {
        x.rankId = self.rankId;
      });
      api
        .rankDetailAdd(self.rankDataSource)
        .then(data => {
          self.loading = false;
          self.$router.push({
            path: "/integral-calculation-management/calculation"
          });
        })
        .catch(error => {
          self.loading = false;
        });
    }
  }
};
</script>

<style scoped>
</style>
